<?php
class Admin_Model_Product extends Zend_Db_Table_Abstract
{
    protected $_name = 'product';
    protected $_primary = 'PRODUCTID';
    
    public function __construct($config = array())
    {
        $this->_db = Zend_Db_Table::getDefaultAdapter();
        parent::__construct($config);
        $writer = new Zend_Log_Writer_Stream(APPLICATION_PATH ."/log.text");
        $this->logger = new Zend_Log($writer);
    }
    
    public function findAll(){
        $data = $this->fetchAll();
        return $data;
    }
    
    public function addNewProduct($params){
        $db = $this->getDefaultAdapter();
        $data = array(
            'NAME' => $params['NAME'],
            'DESCRIPTION' => $params['DESCRIPTION'],
            'PRODUCTCATEGORYID' => $params['PRODUCTCATEGORYID'],
            'PRICE' => $params['PRICE'],
            'IMAGEURL' => $params['IMAGEURL']
        );
        try{
            $db->insert($this->_name, $data);
            return $db->lastInsertId('product', 'PRODUCTID');
        }catch(Zend_Exception $e){
            echo $e->getMessage();
        }
        return 0;
    }
    
    public function updateProduct($params){
        $id = $params['PRODUCTID'];
        echo ($params['IMAGEURL']);
        $db = $this->getDefaultAdapter();
        $data = array();
        if(isset($params['NAME'])) $data['NAME'] = $params['NAME'];
        if(isset($params['IMAGEURL'])) $data['IMAGEURL'] = $params['IMAGEURL'];
        if(isset($params['DESCRIPTION'])) $data['DESCRIPTION'] = $params['DESCRIPTION'];
        if(isset($params['PRODUCTCATEGORYID'])) $data['PRODUCTCATEGORYID'] = $params['PRODUCTCATEGORYID'];
        if(isset($params['PRICE'])) $data['PRICE'] = $params['PRICE'];
        try{
            $db->update($this->_name,$data,"PRODUCTID = ".$id);
        }catch(Zend_Exception $e){
            echo $e->getMessage();
            exit;
        }
    }
    
    public function fetchAllWithCategoryName($storeId, $limit, $offset){
        $data = $this->select();
        $data->setIntegrityCheck(false);
        $data->from(array('p' => 'product'));
        $data->join(array('c' => 'productcategory'), 'p.PRODUCTCATEGORYID = c.PRODUCTCATEGORYID', array('CATEGORYNAME' => 'NAME'));
        $data->where('c.STOREID = ?', $storeId);
        $data->limit($limit,$offset);
        $data = $this->fetchAll($data);
        return $data;
    }
    public function count($storeId){
        $db = Zend_Db_Table::getDefaultAdapter();
        $where = "(1=1)";
        //if($storeId != ""){
        //    $where .= " and STOREID =".$storeId;
        //}
        
        $sql = "select count(*) as COUNT from ".$this->_name ." P WHERE $where";
        $result = $db->query($sql)->fetch();
        return $result['COUNT'];
    }
}
?>